package vue;



import java.io.IOException;

import metier.DefaultHttpClientPerso;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.util.EntityUtils;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.ParseException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.finalprojet.R;

public class EcranAccueil extends Activity {
	
	private EditText Login = null;
    private EditText Pass = null;

	public static final String URLSERVEUR = "https://spartacus.iutc3.unicaen.fr/~projet.echec/";
	
	
	public static final String ADRESSEERVER = "10.0.2.2";

	@Override

	public boolean onKeyDown(int keyCode, KeyEvent event) {

	if (keyCode == KeyEvent.KEYCODE_BACK)  {

		 AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(EcranAccueil.this);
			alertDialogBuilder.setTitle("Attention");
			alertDialogBuilder
				.setMessage("Voulez vous quitter l'application ?")
				.setCancelable(true)
				.setPositiveButton("Quitter",new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog,int id) {
						System.exit(1);
					}
				  });

				AlertDialog alertDialog = alertDialogBuilder.create();
				alertDialog.show();

	return true;

	}

	return super.onKeyDown(keyCode, event);

	}
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.accueil);
    
    Intent Intent = this.getIntent();
  
      Login = (EditText)findViewById(R.id.Login);
      Pass = (EditText)findViewById(R.id.Password);
      Button signin = (Button)findViewById(R.id.SignIn);
      Button logon = (Button)findViewById(R.id.LogIn);
    
        
     Login.setText("adem");
     Pass.setText("ademadem");
     
     
     if ( Intent.getStringExtra("pseudo") != null )
     {
    	 Login.setText(Intent.getStringExtra("pseudo"));
    	 Pass.setText("");
     }
      

     
     if  (!this.isNetworkAvailable() )quit();
    	
   
    signin.setOnClickListener( new OnClickListener() 
    {
		
		public void onClick(View v) 
			{
			 if  (!isNetworkAvailable() ) quit();
			 
			
			
				Intent nextScreen = new  Intent (getApplicationContext (), SignIn.class );
				startActivity (nextScreen);
			
			}
	});
    
    
    
    logon.setOnClickListener(new OnClickListener() 
    {
		
		public void onClick(View v) 
		
			{
			 if  (!isNetworkAvailable() ) quit();

			    String login = Login.getText().toString();
		        String pass1 = Pass.getText().toString();
		      
			  boolean erreur = false;
		        String err = "";
		        
		       if (login.isEmpty() || pass1.isEmpty()  ) { erreur = true ; err+="Vous devez remplir les champs du formulaire\n";}

		       if ( pass1.length() < 8) {erreur = true; err+="Le Mot de passe doit comporter au moins 8 caractères";}
		        	
		       if ( erreur ) Toast.makeText(getApplicationContext(), err, Toast.LENGTH_LONG).show();
		       
		       else
		       {
			 httpTasks req = new httpTasks();
			 String[] parametre =  {Login.getText().toString(),Pass.getText().toString()};
			 req.execute(parametre);
			
		       }
		       
			 
			}
	});
  
}
   
    
    

    public class httpTasks extends AsyncTask< String[], Void, String>   
    {


    	 protected String doInBackground(String[]... arg0) {
    	
    		 
    		 DefaultHttpClientPerso httpclient = new DefaultHttpClientPerso();
    		
    		 	String[] arg = arg0[0];
	    		String pseudo = arg[0];
	    		String password = arg[1];
	    
	    		HttpGet httpget = new HttpGet(URLSERVEUR+"/android/connexion.php?pseudo="+pseudo+"&password="+password);
    	

    			HttpResponse response = null;
    			String responseString = null;
    			
    			 try
    			 {
    			
    				 response = httpclient.execute(httpget);
    			 } catch (ClientProtocolException e) {
    				 e.printStackTrace();
    			 } catch (IOException e) {
    				 e.printStackTrace();
    			 } 
    			    
    			 
    			 HttpEntity entity = response.getEntity();
    			 
    			 if ( entity != null )
    				 try 
    			 	{
    					 responseString = EntityUtils.toString(entity);
    			 	}
    			 catch (ParseException e) 
    			 		{
    					 e.printStackTrace();
    				    } 
    			 catch (IOException e) {
    				     e.printStackTrace();
    				    }
    			return responseString;

    				 	}


    		protected void onPostExecute(String result) 
    		{
    			String toast = null;
    			try {
					
    				
    				//JSONArray main = new JSONArray(result);
    				JSONObject main =new JSONObject(result);
    				String erreur = main.get("error").toString();
    				
    				//Toast.makeText(getApplicationContext(),erreur,Toast.LENGTH_LONG).show();	
    				if ( erreur.contains("p") )
    					
    				{
    					
    					
    					
    					
    					if (  erreur.contains("pass") ) 
    					{
    						
    						toast = "Erreur de mot de passe";
    						Toast.makeText(getApplicationContext(),toast,Toast.LENGTH_SHORT).show();
    					}
    					
    					if (  erreur.contains("pseudo") )
        				{
    						
    						
        					toast = "Pseudo inexistant";
        					Toast.makeText(getApplicationContext(),toast,Toast.LENGTH_SHORT).show();
        				}
    					
    					
    				}
    				
    				
    				
    					
    				

    				else 
    					{
    					
    					toast = "Vous êtes connecté en tant que " + main.get("pseudo").toString();
    					Toast.makeText(getApplicationContext(),toast,Toast.LENGTH_SHORT).show();
    					Intent nextScreen = new  Intent (getApplicationContext(), DashBoard.class );
        				nextScreen.putExtra("id",main.get("id").toString() );
        				nextScreen.putExtra("pseudo", main.get("pseudo").toString());
        				startActivity (nextScreen);
        				
        			
    					}
    				
    				
    		
    				
				} catch (Exception e) {
					Toast.makeText(getApplicationContext(),e.toString(),Toast.LENGTH_LONG).show();
				}
    			
    			
    			
  
    			
    				
    			}
    			

    			
    	
    }
    
    private boolean isNetworkAvailable() {
	    ConnectivityManager connectivityManager 
	          = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
	    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
	    return activeNetworkInfo != null;
	}
    
    private void quit() {
    	 AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(EcranAccueil.this);
			alertDialogBuilder.setTitle("Attention");
			alertDialogBuilder
				.setMessage("L'application n'ayant pas d'accès Internet.\nL'application va quitter")
				.setCancelable(false)
				.setPositiveButton("ok",new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog,int id) {
						System.exit(1);
					}
				  });

				AlertDialog alertDialog = alertDialogBuilder.create();
				alertDialog.show();
 	 
 	 
	}
    
    
    			

}

